const express = require('express')
const cors = require('cors')
const os = require('os')
const http = require('http')
const https = require('https')
const fs = require('fs')
const session = require('express-session')
const WebSocketServer = require('./src/websocket/wsServer')
const monitorMiddleware = require('./src/middlewares/monitor.js')
const monitorWS = require('./src/websocket/monitorWsServer.js')
require('dotenv').config()
const path = require('path')

// 导入数据库连接测试
const { testConnection } = require('./src/config/database')

const userRoutes = require('./src/routes/userRoutes')
const userTestRoutes = require('./src/routes/userTestRoutes')
const anchorRoutes = require('./src/routes/anchorRoutes')
const businessRoutes = require('./src/routes/businessRoutes')
const screenRoutes = require('./src/routes/screenRoutes')
const taoqiAdminRoutes = require('./src/routes/taoqiAdminRoutes')
const trafficRoutes = require('./src/routes/trafficRoutes')
const zhoudao1Routes = require('./src/routes/zhoudao1Routes')
const gaoxinRoutes = require('./src/routes/gaoxinRoutes')
const fileRoutes = require('./src/routes/fileRoutes')
const cityRoutes = require('./src/routes/cityRoutes')
const luluRoutes = require('./src/modules/lulu/luluRoutes')
const jrdRoutes = require('./src/modules/jrd/routes')
const trafficReleaseRoutes = require('./src/modules/trafficRelease/routes')
const errorHandler = require('./src/middlewares/errorHandler')

// const deepseekai = require("./src/deepseekai/index")

// 导入响应组件用于全局错误处理
const { ResponseComponent } = require('./src/components')

const app = express()
const port = process.env.PORT || 2230
const httpsPort = process.env.HTTPS_PORT || 3443

// SSL 证书配置
let credentials = null
let httpsServer = null

try {
  const privateKey = fs.readFileSync('server.key', 'utf8')
  const certificate = fs.readFileSync('server.crt', 'utf8')

  // 检查证书格式是否正确
  if (!privateKey.includes('-----BEGIN') || !certificate.includes('-----BEGIN')) {
    throw new Error('证书文件格式不正确。请确保它们是有效的 PEM 格式。')
  }

  credentials = { key: privateKey, cert: certificate }
  console.log('SSL 证书加载成功。正在尝试启动 HTTPS 服务器...')
} catch (error) {
  console.warn('警告：无法配置 HTTPS 服务器。HTTPS 将不会启动。')
  console.warn('错误详情:', error.message)

  if (error.code === 'ENOENT') {
    console.warn('请确保 server.key 和 server.crt 文件存在于项目根目录，或已正确配置路径。')
  } else if (error.code === 'ERR_OSSL_PEM_NO_START_LINE' || error.message.includes('格式不正确')) {
    console.warn('\n请确保证书文件符合以下 PEM 格式规范：')
    console.warn('server.key 文件内容示例：')
    console.warn('-----BEGIN PRIVATE KEY-----')
    console.warn('... 私钥内容 ...')
    console.warn('-----END PRIVATE KEY-----\n')

    console.warn('server.crt 文件内容示例：')
    console.warn('-----BEGIN CERTIFICATE-----')
    console.warn('... 证书内容 ...')
    console.warn('-----END CERTIFICATE-----')

    console.warn('\n如果您只是想进行开发测试，可以尝试以下步骤：')
    console.warn('1. 删除现有的 server.key 和 server.crt 文件')
    console.warn('2. 使用以下 OpenSSL 命令生成自签名证书（需要安装 OpenSSL）：')
    console.warn('   openssl req -x509 -newkey rsa:2048 -keyout server.key -out server.crt -days 365 -nodes -subj "/CN=localhost"')
  }
}

// 中间件
app.use(cors())
app.use(express.json())
// 解析 URL 编码的请求体（表单提交），extended: true 表示使用 qs 库解析，支持复杂对象
app.use(express.urlencoded({ extended: true }))

// 配置 session
app.use(
  session({
    secret: process.env.SESSION_SECRET || 'lulu-captcha-secret-key',
    resave: false,
    saveUninitialized: false,
    cookie: {
      secure: false, // 在开发环境设为false，生产环境使用HTTPS时设为true
      maxAge: 1000 * 60 * 30, // 30分钟过期
    },
  }),
)

// 配置静态文件服务
app.use(express.static(path.join(__dirname, 'src/public')))

// 接口调用监控中间件（放在路由前，捕获所有请求/响应）
app.use(monitorMiddleware)

// 路由
app.use('/api/users', userRoutes)
app.use('/proxy', anchorRoutes)
app.use('/api', businessRoutes)
app.use('/local', screenRoutes)
app.use('/local', taoqiAdminRoutes)
app.use('/trafficLocal', trafficRoutes)
app.use('/api/files', fileRoutes)
app.use('/api/cities', cityRoutes)
app.use('/lulu', luluRoutes)
app.use('/jrd', jrdRoutes)
app.use('/trafficRelease', trafficReleaseRoutes)

app.use('/zhoudao1', zhoudao1Routes)
app.use('/gaoxin', gaoxinRoutes)

// 本地调试接口
app.use('/localApi', userTestRoutes)

// 404 处理
app.use(ResponseComponent.notFoundHandler)

// 全局错误处理中间件
app.use(ResponseComponent.globalErrorHandler)

// 获取本机IP地址
function getIPAddress() {
  const networkInterfaces = os.networkInterfaces()
  if (!networkInterfaces) {
    return '127.0.0.1'
  }

  for (const name of Object.keys(networkInterfaces)) {
    const interfaces = networkInterfaces[name]
    if (!interfaces) {
      continue
    }

    for (const net of interfaces) {
      // 过滤出IPv4非loopback地址
      if (net && net.family === 'IPv4' && !net.internal) {
        return net.address
      }
    }
  }
  return '127.0.0.1' // 如果没有找到合适的IP，返回localhost
}
const ipAddress = getIPAddress()

// 创建HTTP服务器
const httpServer = http.createServer(app)

// 如果证书加载成功，则创建HTTPS服务器
if (credentials) {
  httpsServer = https.createServer(credentials, app)
}

// 初始化WebSocket服务器
// const wss = new WebSocketServer(httpsServer)
monitorWS.init(httpServer)

// 启动HTTP服务器
httpServer.listen(Number(port), '0.0.0.0', async () => {
  console.log(`HTTP Server is running on http://localhost:${port}`)
  console.log(`HTTP Server is running on http://${ipAddress}:${port}`)
  console.log(`接口监听 http://localhost:${port}/monitor.html`)

  // 测试数据库连接
  await testConnection()
})

// 如果HTTPS服务器已创建，则启动它
if (httpsServer) {
  httpsServer.listen(Number(httpsPort), '0.0.0.0', () => {
    console.log(`HTTPS Server is running on https://localhost:${httpsPort}`)
    console.log(`HTTPS Server is running on https://${ipAddress}:${httpsPort}`)
    // console.log(`WebSocket server is running on wss://localhost:${httpsPort}`)
  })
}
